package cn.jly.springboot24.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Map;

/**
 * @PackageName cn.jly.springboot24.controller
 * @ClassName FormUploadController
 * @Description 测试文件上传
 * @Author 姬岚洋
 * @Date 2021/1/17 下午 10:00
 */
@Slf4j
@Controller
public class FormUploadController {

    /**
     * 自定封装上传的文件 MultipartFile
     *
     * @param username
     * @param email
     * @param headerImg
     * @param photos
     * @return
     */
    @PostMapping("/upload")
    public String upload(@RequestParam("username") String username,
                         @RequestParam("email") String email,
                         // 上传单文件
                         @RequestPart("headerImg") MultipartFile headerImg,
                         // 上传多文件
                         @RequestPart("photos") MultipartFile[] photos,
                         Map<String, Object> map
    ) throws IOException {
        log.info("上传的信息：email = {}, username = {}, headerImg = {}, photos = {}",
                username, email, headerImg.getSize(), photos.length);
        map.put("username", username);
        map.put("email", email);
        map.put("headerImg_size", headerImg.getSize());
        map.put("photos_number", photos.length);

        // 文件上传并保存
        if (!headerImg.isEmpty()) {
            // 保存到文件服务器
            final String originalFilename = headerImg.getOriginalFilename();
            headerImg.transferTo(new File("d:/Temp/" + originalFilename));
        }

        if (photos.length > 0) {
            for (MultipartFile photo : photos) {
                if (!photo.isEmpty()) {
                    photo.transferTo(new File("d:/Temp/photos/" + photo.getOriginalFilename()));
                }
            }
        }

        return "success";
    }

    /**
     * 去首页
     *
     * @return
     */
    @GetMapping("/index")
    public String toUploadPage(){
        return "index";
    }
}
